package net.tycmc.bulb.note.core.thread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import org.apache.commons.configuration.ConfigurationException;

import net.sf.json.JSONObject;
import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.bulb.common.util.StringUtil;
import net.tycmc.bulb.note.core.consumer.fltnote.AccountBehaviorAnalysisConsumer;

import com.tycmc.functions.util.DynamicReadConfig;



public class AccountbaRunner implements Runnable {
	public Map<String,Object>param;
	public AccountbaRunner(Map<String, Object> param){
		super();
		this.param = param;
	}
	
	@Override
	public void run() {	
		    Map<String,Object> wSrcInfoMap = new HashMap<String, Object>();
			 String UserIp=MapGetter.getString(param,"UserIp");
			 //根据用ip获取归属地地址
		     String IpAddress = Test.getAddressURL(UserIp);
		     String wSrcInfo = downloadNetSimple(IpAddress);
		     if(wSrcInfo!=null&&!"".equals(wSrcInfo)){
		    	 wSrcInfoMap = JsonConvertMaps(wSrcInfo);
		    	 param.put("IpAddr", MapGetter.getString(wSrcInfoMap,"country")+":"+MapGetter.getString(wSrcInfoMap,"city"));
		     }else{
		    	 param.put("IpAddr", "获取归属地失败");
		     }
		     //将数据写入文件
		     writeFiles(param);
       
	}
	
	//写入文件方法
	public  void writeFiles(Map<String,Object> param) {
		   try {
			String msgTime=MapGetter.getString(param, "msgTime")+"@@";
			String browserName=MapGetter.getString(param, "browserName")+"@@";
			String OS=MapGetter.getString(param, "OS")+"@@";
			String ModelOperate=MapGetter.getString(param, "ModelOperate")+"@@";
			String Account=MapGetter.getString(param, "Account")+"@@";
			String UserName=MapGetter.getString(param, "UserName")+"@@";
			String accountType=MapGetter.getString(param, "accountType")+"@@";
			String UserIp=MapGetter.getString(param, "UserIp")+"@@";
			String IpAddr=MapGetter.getString(param, "IpAddr")+"@@";
			String searchParamString=MapGetter.getString(param, "searchParamString");
			if(AccountBehaviorAnalysisConsumer.sbes.length()>1024){//开始写入 1kb则存储
				String result=AccountBehaviorAnalysisConsumer.sbes.toString();
				AccountBehaviorAnalysisConsumer.sbes=new StringBuffer();
				String path = "";
				try {
					path = DynamicReadConfig.getConfigProperty("config.properties", "Url");
				} catch (ConfigurationException e) {
					e.printStackTrace();
				}
				Date date = new Date();
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				String nowtime = format.format(date);
				path = path+nowtime+".txt";
			    //FileOutputStream bw = new FileOutputStream(path,true);//重复写入，避免覆盖
			    //FileChannel fc=bw.getChannel();
				RandomAccessFile bw=new RandomAccessFile(path,"rw");
				FileChannel fc=bw.getChannel();
				FileLock lock=null;
			    while(true){
			    	try{
			    		lock=fc.lock();
			    		if(null!=lock){
			    			break;
			    		}
			    		
			    	}catch(OverlappingFileLockException e){
			    		try {
							Thread.sleep(500);
						} catch (InterruptedException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
			    		//System.out.println("有其他线程正在操作该文件;"+e);
			    	}
		    		
			    	}
			    if(lock!=null&&lock.isValid()){
			    	 bw.seek(bw.length());
		    		bw.write(result.getBytes());//换行符
			 		lock.release();
			 		lock.close();
			 		fc.close();
			 		bw.close();	
			 		 result="";
			    }
			}else{
				AccountBehaviorAnalysisConsumer.sbes.append("\r\n"+msgTime+browserName+OS+ModelOperate+Account+UserIp+IpAddr+searchParamString);
			}
		   } catch (IOException e) {
		    e.printStackTrace();
		   }
		  }
	
	public static String downloadNetSimple(String netUrl) {
		StringBuffer retBuff = new StringBuffer();		
		if(StringUtil.isNullOrEmpty(netUrl)){
			BufferedReader br = null;
			InputStream inStream = null;
			URL url = null;
			try {
				url = new URL(netUrl);
			} catch (MalformedURLException e1) {
				e1.printStackTrace();
			}
			
			try {
				URLConnection conn = url.openConnection();
				inStream = conn.getInputStream();
				br = new BufferedReader(new InputStreamReader(inStream,"utf-8"));
				String line = null;
				while((line = br.readLine()) != null){
					retBuff.append(line);
				}
			} catch (FileNotFoundException e) {
				//e.printStackTrace();
				System.out.println("接口获取ip对应归属地数据失败！！！");
			} catch (IOException e) {
				//e.printStackTrace();
				System.out.println("接口获取ip对应归属地数据失败！！！");
			}finally{
				try {
					if(br != null)
						br.close();
					if(inStream != null)
						inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return retBuff.toString();
	}
	/**将JSON串变成map
     * @param jsonStr
     * @return
     */
	  public Map<String, Object> JsonConvertMaps(String jsonStr) {
		  if(!StringUtil.isValid(jsonStr)){
			  return null;
		  }
			JSONObject json = JSONObject.fromObject(jsonStr);
			Map<String, Object> map = new HashMap<String, Object>();
			int code = json.getInt("code");
			map.put("code",code);
			if (code==0) {
				String result = json.getString("data");
				//result = result.substring(1, result.length()-1);
				JSONObject  jsonobject = JSONObject.fromObject(result);
				Iterator it = jsonobject.keys();
				while (it.hasNext()) {
					String key = String.valueOf(it.next());
					String value = (String) jsonobject.get(key);
					map.put(key,value);			
					
				}

			}
			return map;
		}

}
//返回ip请求路径
class Test { 
    public static String getAddressURL(String UserIp){  
    	String IpAddr="http://ip.taobao.com/service/getIpInfo.php?ip="+UserIp;
    	return IpAddr;  
    }   
}

